import { useRouter, useSearchParams } from "@/router/hooks";
import { useUserActions, useUserToken } from "@/store/userStore";
import { useEffect } from "react";
import { getToken } from '@/api/app/ssoApp'
const CallbackIndex = () => {
  const searchParams = useSearchParams()
  const router = useRouter()
  const ACCESS_TOKEN = localStorage.getItem('access_token')
  const { setUserToken } = useUserActions()
  const init = () => {
    let path = decodeURIComponent(searchParams.get('state'))
    const code = decodeURIComponent(searchParams.get('code'))
    if (ACCESS_TOKEN) {
      setUserToken(ACCESS_TOKEN)
      router.push(import.meta.env.VITE_APP_HOMEPAGE)
      return
    }
    //单点回调的置换token
    getToken({
      grant_type: 'authorization_code',
      oauth_timestamp: new Date().getTime(),
      client_id: 'ssoclient',
      client_secret: '3990fa6d7dcd8442d598bd8412e776a5160d',
      code,
      redirect_uri: location.origin + '/integration/callback'
    }).then(res => {
      setUserToken(res.access_token)
      if (path) {
        if (path.includes('http')) {
          if (!path.includes('?')) {
            path += '?'
          }

          for (const key of searchParams.keys()) {
            if (key !== 'state' && key !== 'code') {
              if (!path.includes('&')) {
                path += `${key}=${searchParams.get(key)}`
              } else {
                path += `&${key}=${searchParams.get(key)}`
              }
            }
          }

          location.href = path
          return
        }
      }
    })
  }
  useEffect(() => {
    init()
  }, [])
  return (<div className="CallbackIndex"></div>);
}

export default CallbackIndex;
